<?php
namespace Crm\Model;

/**
 * 商品分类数据库模型
 *
 * @author SoChishun <14507247@qq.com>
 * @version 1.0
 * @since 1.0.0 <2015-4-2> SoChishun Added.
 */
class ProductCategoryModel extends AppbaseModel {

    /**
     * 数据表名称
     * @var string
     */
    protected $tableName = 'tproduct_category';
    
    /**
     * 字段定义
     * @var array
     */
    protected $fields = array('id', 'category_name', 'parent_id', 'type_id', 'item_count', 'visit_count', 'meta_keywords', 'meta_description', 'image_url', 'link_url', 'user_id', 'access_permission', 'remark', 'ex_tags', 'ordinal', 'state', 'create_time', 'site_id', '_pk' => 'id', '_autoinc' => true);
    
    /**
     * 命名范围
     * @var array
     */
    protected $_scope = array(
        'treeselect' => array(
            'field' => 'id, category_name'
        ),
        'treetable' => array(
            'field' => array('id', 'category_name', 'parent_id', 'ordinal', 'remark', 'state', 'create_time'),
            'order' => 'ordinal,id'
        ));
    
    /**
     * 是否批量验证
     * @var boolean
     */
    protected $patchValidate = true;
    
    /**
     * 验证规则
     * @var array
     */
    protected $_validate = array();
    
    /**
     * 自动填充
     * @var array
     */
    protected $_auto = array();

    /**
     * 返回树形列表或刷新缓存
     * 
     * @param string $scope 命名范围
     * @param boolean $refresh 是否强制刷新缓存
     * @since 1.0 <2015-4-2> SoChishun Added.
     */
    public function get_tree_list($scope = '', $refresh = false) {
        if (!$scope) {
            $scope = 'treeselect';
        }
        return $this->base_get_tree_list('Product/category_' . $scope, $scope, $refresh);
    }

    /**
     * 保存角色
     * @return true|string|array
     * @since 1.0 2015-3-6 by sutroon
     */
    public function save_item() {
        $rules = array(
            array('category_name', 'require', '类别名称必须填写!', 0, 'regex', 1),
            array('state', 'number', '状态有误!'),
        );
        if (!$this->validate($rules)->create()) {
            $this->base_return_array(false, $this->getError());
        }
        if ($this->data['id']) {
            $result = $this->save();
        } else {
            $result = $this->add();
        }
        // 刷新缓存
        $this->get_tree_list('treeselect',true);
        $this->get_tree_list('treetable',true);
        return $this->base_return_array($result);
    }
}